<template>
    <view style="height: 100%">
        <view class="user-head">
            <view class="center" @tap="userdata">
                <view class="user-img">
                    <image :src="'data:image/png;base64,' + userInfo.avatar" v-if="isLogin" />
                    <image src="/static/images/logo.jpg" v-if="!isLogin" />
                </view>
                <view class="user-text">
                    <text class="text">{{ userInfo.userName }}</text>
                </view>
            </view>
        </view>
        <view class="list" v-if="isLogin">
            <!--<view class="item" bindtap="dating">
              <image src="../../images/dd.png"/>我的预约
              <text class="jump">〉</text>
            </view>-->
            <view class="item" @tap="order">
                <image src="/static/images/dingdan.png" />
                我的订单
                <text class="jump">〉</text>
            </view>
            <view class="item" @tap="market">
                <image src="/static/images/ding.png" />
                我的分销
                <text class="jump">〉</text>
            </view>
            <!--<view class="item" @tap="shoppingcar">
                <image src="/static/images/gouwuche_s.png" />
                购物车
                <text class="jump">〉</text>
            </view>-->
        </view>        
        <!--<button class="weui-btn" type="primary" v-if="!isLogin">登录</button>-->
        <button class="weui-btn" type="warn" @tap="loginOut" v-if="isLogin">退出登录</button>
        <view class="xw-login-form" v-if="!isLogin">
          <form @submit="sublogin">
            <view class="xw-login-form-item">
              <view class="xw-login-form-label">手机号</view>
              <input class="xw-login-form-input" maxlength="11" placeholder="请填写手机号" type="text" name="phone" v-model="form.phone" />
              <view class="login-form-icon login-form-seepass">
                <image src="../../static/img/l01.png" mode="aspectFill"></image>
              </view>
            </view>
            <view class="xw-login-form-item" v-if="!logintype">
              <view class="xw-login-form-label">密码</view>
              <input class="xw-login-form-input" placeholder="请输入密码" name="password" v-model="form.password" :password="showPassword" type="text" />
              <view class="login-form-icon login-form-seepass" @click="changePassword">
                <image src="../../static/img/l03.png" mode="aspectFill" v-if="showPassword"></image>
                <image src="../../static/img/l04.png" mode="aspectFill" v-else></image>
              </view>
            </view>
            <view class="xw-login-form-item" v-if="logintype">
              <view class="xw-login-form-label">验证码</view>
              <input class="xw-login-form-input" placeholder="请填写验证码" name="code" v-model="form.code" type="text" />
              <view class="wx-btn wx-btn-info" @click="getMsgCode()" v-if="!loading">获取验证码</view>
              <view class="wx-btn wx-btn-info" v-else>{{time}}秒后重试</view>
            </view>
            <text class="xw-login-form-code" v-if="logintype" @click="changeLogintype">使用密码登录</text>
            <text class="xw-login-form-code" v-if="!logintype" @click="changeLogintype">使用短信验证码登录</text>
            <view class="xw-login-form-code" @click="goForgetPass">新注册或忘记密码</view>
            <button class="wx-btn wx-btn-info xw-login-form-btn" form-type="submit">登录</button>
            <view class="login-agree">
              <view class="login-agree-checkd">
                <label for="agree">
                  <checkbox id="agree" style="transform:scale(0.7)" :checked="agree" @click="agree = !agree"/>
                  <text class="login-agree-btn">已阅读并同意</text>
                </label>
              </view>
              <view class="login-agree-text" @click="goagreement()">《隐私及服务协议》</view>
            </view>
          </form>
        </view>
    </view>
</template>

<script>
var app = getApp();
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
var util = require('../../utils/util.js');
export default {
    data() {
        return {
            isLogin: false,
            userInfo: {
                avatar: '',
                userName: ''
            },            
            form: {
              phone: "",
              password: ""
            },
            loading: false,
            timer: null,
            time: 60,
            logintype: false,
            showPassword: true,
            agree: false,
        };
    },
    onShow: function () {
        this.onShowClone3389();
        let local = location.href;
        let userId = util.getParamQueryString(local, "userId");
        let code = util.getParamQueryString(local, "code");
        if (userId&&code) {
          this.userId = userId;
          this.getOpen(userId, code);
        }
    },
    methods: {
        async getOpen(userId, code) {
            await http.httpPost(
                config.clubApi.getopenid,
                {
                    userId: userId,
                    code: code,
                    appid:config.APPID,
                    ywtype:3
                },
                function (res) {
                }
            );
        },
        goForgetPass(){
          uni.navigateTo({
            url:'../forget/index'
          })
        },
        changeLogintype() {
          this.logintype=!this.logintype
          if(this.logintype){
            this.form = {
              phone: this.form.phone,
              code: ""
            }
          }
          if(!this.logintype){
            this.form = {
              phone: this.form.phone,
              password: ""
            }
          }
        },
        changePassword() {
          this.showPassword = !this.showPassword;
        },
        goagreement() {
          window.open('http://train.shudingkj.com/am.html')
        },
        getMsgCode() {
          var reg = /^1[0-9]{10,10}$/;
          if(!this.form.phone||!reg.test(this.form.phone)){
            uni.showToast({
              title:'请输入正确的手机号',
              icon:'none'
            })
            return
          }
          this.loading = true
          this.timer = setInterval(() => {
            this.time--
            if (this.time <= 0) {
              clearInterval(this.timer)
              this.loading = false
              this.time = 60
            }
          }, 1000)
          http.httpGet(
              config.clubApi.getPhoneCode,
              {
                phone:this.form.phone                
              },
              function (res) {
                  if (res.code == '200') {
                    uni.showToast({
                      title:'验证码已发送至你的手机',
                      icon:'none'
                    })
                  }
              }
          );
        },
        rMathfloor(min, max) { //返回包括最大/小值
          return Math.floor(Math.random() * (max - min + 1)) + min
        },        
        sublogin(e) {
          var rules = {
            phone: {
              rules: [{
                checkType: "required",
                errorMsg: "请填写手机号码"
              }, {
                checkType: "phone",
                errorMsg: "请填写正确的手机号码"
              }]
            },
            password: {
              rules: [{
                checkType: "required",
                errorMsg: "请输入密码"
              }, {
                checkType: "string",
                checkRule: "8,20",
                errorMsg: "至少输入8-20位"
              }]
            },
            code: {
              rules: [{
                checkType: "required",
                errorMsg: "请输入验证码"
              }]
            }
          };
          var formData = JSON.parse(JSON.stringify(this.form));
          var checkRes = util.checkByRules(formData, rules);
          var that = this;
          let inviteId = uni.getStorageSync('inviteId');
          if (checkRes=='') {
            if (!this.agree) {
              uni.showToast({
                title: '请先同意《隐私及服务协议》',
                icon: 'none'
              });
              return;
            }
            uni.showLoading()
            if (!that.logintype) {
              http.httpPost(
                  config.clubApi.login,
                  {
                    userName: that.form.phone,
								    password: that.form.password,
                    inviteId: inviteId == null || inviteId == '' ? 0 : inviteId
                  },
                  function (res) {
                      if (res.code == '200') {
                        uni.setStorageSync('inviteId', null);
                        if (!res.data.hopenId) {
                          that.wxAuthorization(res.data.userId);
                        }
                        app.globalData.setUserInfo(res.data);
                        uni.hideLoading()
                        setTimeout(() => {
                          that.userInfo = uni.getStorageSync('user');
                          that.onShowClone3389({});
                        }, 2000);
                      }
                  }
              );
            }
            if (that.logintype) {
              http.httpPost(
                  config.clubApi.loginByCode,
                  {
                    appid: config.APPID,
                    ywtype: 3,
                    userName: that.form.phone,
								    phoneCode: that.form.code
                  },
                  function (res) {
                      if (res.code == '200') {
                        uni.setStorageSync('inviteId', null);
                        if (!res.data.hopenId) {
                          that.wxAuthorization(res.data.userId);
                        }
                        app.globalData.setUserInfo(res.data);
                        uni.hideLoading()
                        setTimeout(() => {
                          that.userInfo = uni.getStorageSync('user');
                          that.onShowClone3389({});
                        }, 2000);
                      }
                  }
              );
            }
          } else {
            uni.showToast({
              title: checkRes,
              icon: "none",
              position: 'bottom'
            });
          }
        },
        getUrlParams(name) {
          let local = location.href; 
          var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");				
          if (reg.test(local)) {
            return unescape(RegExp.$2.replace(/\+/g, " "));
          }
          return "";
        },
        // 微信授权
        wxAuthorization(userId) {          
          let code = this.getUrlParams("code");
          //是否存在code
          //如果不存在code则跳转授权
          if (!code) {
            // 本地路径
            let local = `http://train.shudingkj.com/pages/user/index?userId=${userId}`
            // 公众号或测试号appid 
            let appid = config.APPID;
            //不存在就打开下面的地址进行授权
            let authPageBaseUri = "https://open.weixin.qq.com/connect/oauth2/authorize";
            let scope = 'snsapi_base';
            authPageBaseUri +='?appid='+ appid+'&redirect_uri='+encodeURIComponent(local)+'&response_type=code&scope='+scope+'&state=STATE&connect_redirect=1#wechat_redirect';
            window.location.href = authPageBaseUri;
          }
        },
        onShowClone3389: function () {
            var that = this;
            let userInfo = uni.getStorageSync('user');
            if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
                that.setData({
                    isLogin: true,
                    userInfo: userInfo
                });
            }
        },

        userdata: function () {
            uni.navigateTo({
                url: '/pages/userdata/index'
            });
        },

        address: function () {
            uni.navigateTo({
                url: '/pages/address/index'
            });
        },

        dating: function () {
            uni.navigateTo({
                url: '/pages/dating/index'
            });
        },

        order: function () {
            uni.navigateTo({
                url: '/pages/order/index'
            });
        },

        market: function () {
            uni.navigateTo({
                url: '/pages/market/index'
            });
        },

        shoppingcar: function () {
            uni.navigateTo({
                url: '/pages/shoppingcar/index'
            });
        },

        // 退出登录
        loginOut() {
            uni.request({
                method: 'GET',
                url: config.BASE_URL + config.clubApi.logout,
                header: {
                    'U-TOKEN': uni.getStorageSync('user') ? uni.getStorageSync('user').token : config.clubApi.logout,
                    userId: uni.getStorageSync('user').userId
                },
                success: (res) => {
                    if (res.data.code == '200') {
                        this.setData({
                            isLogin: false,
                            userInfo: {}
                        });
                        // 清空缓存
                        uni.setStorageSync('user', null);
                    }
                }
            });
        }        
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
